﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using System.IO;
using System.Xml;
using System.Web;
using System.Runtime.InteropServices;
using System.IO.Ports;

using weiqijiance;
using CCWin;

namespace weiqijiance
{
    public partial class BiaoDing : CCSkinMain
    {
        // /声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        //声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        private string sPath = null;



        public float[] fAIDataZero = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//零点漂移值
        public int m_flushuAI;//AI模拟信号路数
        public int m_flushuTI;//AI模拟信号路数

        public bool btdsfsz;//表示选中的设备是否有设置了通道
        public static string sSetTongDao;

        public CDataClass dataBD;

      

        

        public mainform m_mainform;
        public  float fcaiyangzhi;
        public float fjisuanzhi;

        public string sdengpaiSH;
        public string sdengpaiXH;

        public int ipinglv;

        public Thread t1;

        public string sname;

        public BiaoDing()
        {
            InitializeComponent();
            sname = "";
            dataBD = new CDataClass();
            btdsfsz = false;
            fcaiyangzhi = 0;
            m_flushuAI = 0;
            m_flushuTI = 0;
            DogObject objex = new DogObject();

            if (!objex.verify())
            {
                skinBut_add.Visible = false;
                skinBut_del.Visible = false;
                skinBut_set.Visible = false;
            }

            inicbx(com_shebei);
            t1 = new Thread(new ThreadStart(Thread1));

            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            x = this.Width;
            y = this.Height;
            setTag(this);
           
           
        }
        public void inicbx(ComboBox cbx)
        {
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
            string path1 = string.Format(@"{0}", path);
            Ini(path1);


            string sSetneirong ="";
            sSetneirong = ReadValue("通道设置", "模拟信号1");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号2");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号3");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号4");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号5");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号6");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号7");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号8");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号9");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "模拟信号10");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "速度1");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "速度2");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "速度3");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           sSetneirong = ReadValue("通道设置", "速度4");
           if (sSetneirong != "")
           {
               cbx.Items.Add(sSetneirong);
           }
           bool bcg = false;
           for (int i = 0; i < cbx.Items.Count; i++)
           {
               if (cbx.Items[i].ToString().Contains("测功力"))
               {
                   bcg = true;
               }
           }
            if(bcg)
                cbx.Items.Add("涡流输出");
            
                
              
        }
        #region 控件大小随窗体大小等比例缩放
        private float x;//定义当前窗体的宽度
        private float y;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            //遍历窗体中的控件，重新设置控件的值
            foreach (Control con in cons.Controls)
            {
                //获取控件的Tag属性值，并分割后存储字符串数组
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    //根据窗体缩放的比例确定控件的值
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        #endregion
        //ini文件
        public void Ini(string path)
        {
            this.sPath = path;
        }
        public void Writue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
        //ini文件
        private delegate void FlushClient();//代理
        private void xianshiCYZ()
        {
            if (this.text_caiyanzhi.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(xianshiCYZ);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                //this.text_caiyanzhi.Text = string.Format(@"{0}", fcaiyangzhi);
                this.text_caiyanzhi.Text = fcaiyangzhi.ToString("0.00");
            }
        }
        private void xianshiJSZ()
        {
            if (this.text_jisuanzhi.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(xianshiJSZ);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
               // this.text_jisuanzhi.Text = string.Format(@"{0}", fjisuanzhi);
                this.text_jisuanzhi.Text = fjisuanzhi.ToString("0.00");
            }
        }


        public void Thread1()
        {
            for (; ; )
            {
                getbiaodingshuju();
                if (!che_zdcy.Checked)
                {
                    break;
                }
                Thread.Sleep(300);
            }
        }

        public void getlingdian()//获取零点
        {
            for(int i=0;i<10;i++)
            {
                fAIDataZero[i] = m_mainform.DAC.fAIData[i];
            }
            
        }
        public void getbiaodingshuju()
        {
            try
            {

                string path = "";
                path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
                string path1 = string.Format(@"{0}", path);
                Ini(path1);
                if (sname.Contains("涡流输出"))
                {
                    float fcyzls=0;
                    for (int i = 0; i < 10; i++)
                    {
                        string sgetname = ReadValue("通道设置", string.Format(@"模拟信号{0}", i + 1));
                        if (sgetname.Contains("测功力"))
                        {
                            fcyzls += m_mainform.DAC.getjsz(sgetname, m_mainform.DAC.fAIData[i]) - m_mainform.DAC.getjsz(sgetname, fAIDataZero[i]);

                        }
                    }
                    fcaiyangzhi=fcyzls;
                    xianshiCYZ();
                    float fwoliujsz = 0;
                    float.TryParse(txtfs.Text, out fwoliujsz);
                    fjisuanzhi = m_mainform.DAC.getcyz("涡流输出", fwoliujsz);
                    xianshiJSZ();

                }
                else
                {

                    for (int i = 0; i < 10; i++)
                    {
                        string sgetname = ReadValue("通道设置", string.Format(@"模拟信号{0}", i + 1));
                        if (sname == sgetname)
                        {
                            fcaiyangzhi = m_mainform.DAC.fAIData[i];
                            xianshiCYZ();
                            fjisuanzhi = m_mainform.DAC.getjsz(sname, fcaiyangzhi) - m_mainform.DAC.getjsz(sname, fAIDataZero[i]);
                            xianshiJSZ();


                        }
                    }

                    for (int i = 0; i < 4; i++)
                    {
                        if (sname == ReadValue("通道设置", string.Format(@"速度{0}", i + 1)))
                        {
                            fcaiyangzhi = m_mainform.DAC.fTIData[i];
                            xianshiCYZ();
                            fjisuanzhi = m_mainform.DAC.getjsz(sname, fcaiyangzhi);
                            xianshiJSZ();

                        }
                    }
                    sdengpaiSH = string.Format("采样值:{0}", fcaiyangzhi.ToString("0.00"));
                    if (sname.Contains("轮重") || sname.Contains("整备质量") || sname.Contains("悬架"))
                    {
                        sdengpaiXH = string.Format("数值:{0}kg", fjisuanzhi.ToString("0.00"));
                    }
                    else if (sname.Contains("制动力") || sname.Contains("平板前制动") || sname.Contains("平板后制动"))
                    {
                        sdengpaiXH = string.Format("数值:{0}dN", fjisuanzhi.ToString("0.00"));
                    }
                    else if (sname.Contains("侧滑"))
                    {
                        sdengpaiXH = string.Format("数值:{0}m/km", fjisuanzhi.ToString("0.00"));
                    }
                    else if (sname.Contains("测功力"))
                    {
                        sdengpaiXH = string.Format("数值:{0}N", fjisuanzhi.ToString("0.00"));
                    }
                    else if (sname.Contains("速度"))
                    {
                        sdengpaiXH = string.Format("数值:{0}km/h", fjisuanzhi.ToString("0.00"));
                    }
                    m_mainform.flowwq.LedWrite(sdengpaiSH, sdengpaiXH, 1);
                }
                
             
            }
            catch
            { 
            }
              
        }

      

        private void che_zdcy_CheckedChanged(object sender, EventArgs e)
        {
            if (che_zdcy.Checked)
            {
                getlingdian();
                t1 = new Thread(new ThreadStart(Thread1));
                t1.Priority = ThreadPriority.BelowNormal;
                t1.Start();
            }
            else
            {
                //t1.Abort();
                //t1.DisableComObjectEagerCleanup();
            }
        }

        private void but_add_Click(object sender, EventArgs e)
        {
            ListViewItem li = new ListViewItem();
            li.SubItems[0].Text = text_caiyanzhi.Text;
            li.SubItems.Add(text_biaozhunzhi.Text);
            listView1.Items.Add(li);
        }

        private void but_baocun_Click(object sender, EventArgs e)
        {
            string sfr = "";
            string sfs = "";
            float[] ffr = new float[listView1.Items.Count];
            float[] ffs = new float[listView1.Items.Count];
            float [] fcyz= new float[listView1.Items.Count];
            float [] fbdz= new float[listView1.Items.Count];
            int icount = 0;
            int icountds=0;
            foreach (ListViewItem li in listView1.Items)
            {
                float.TryParse(li.SubItems[0].Text.Trim(), out ffr[icount]);
                float.TryParse(li.SubItems[1].Text.Trim(), out ffs[icount++]);

                float.TryParse(li.SubItems[0].Text.Trim(), out fcyz[icountds]);
                float.TryParse(li.SubItems[1].Text.Trim(), out fbdz[icountds]);
                icountds++;

            }
            string sSet = "";

            BubbleSort(fcyz);
            BubbleSort(fbdz);
            sfr = "";
            sfs = "";
            for (int i = 0; i < icountds; i++)
            {
                sfr = sfr + string.Format(@"{0}", fcyz[i]) + ",";
                sfs = sfs + string.Format(@"{0}", fbdz[i]) + ",";
            }
            sSet = sfr + ";" + sfs;

            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\标定数据.ini";
            string path1 = string.Format(@"{0}", path);
            Ini(path1);

            Writue("标定", com_shebei.Text, sSet);

            int iwidth = pictureBox1.Width;
            int iheight = pictureBox1.Height;
            float x1 = 0, y1 = iheight;

            float fx = (ffr[ffr.Length - 1] - ffr[0]) / iwidth;
            float fy = (ffs[ffs.Length - 1] - ffs[0]) / iheight;

            //  float fy = iwidth / ffr.Length - 1;
            //fs为x轴，fr为y轴
            Graphics gas = pictureBox1.CreateGraphics();
            gas.Clear(pictureBox1.BackColor);
            //   Pen p = new Pen(Color.Red, 2);
            for (int i = 0; i < ffr.Length; i++)
            {
                Graphics g = pictureBox1.CreateGraphics();
                //g.Clear(pictureBox1.BackColor);
                Pen p = new Pen(Color.Red, 1);

                float float1 = (ffr[i] - ffr[0]) / fx;
                float float2 = iheight - ((ffs[i] - ffs[0]) / fy);
                g.DrawLine(p, x1, y1, float1, float2);
                x1 = float1;// fx * (ffr[i] - ffr[0]);
                y1 = float2;// fy * (ffs[i] - ffs[0]);
            }

            Graphics gex = pictureBox1.CreateGraphics();
            //g.Clear(pictureBox1.BackColor);
            Pen p1 = new Pen(Color.Green, 1);
            gex.DrawLine(p1, 0, iheight, iwidth, 0);
        }

        private void but_del_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem li in listView1.Items)
            {
                if (li.SubItems[0].Text == text_caiyanzhi.Text)
                {
                    listView1.Items.Remove(li);
                    break;
                }
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem li in listView1.SelectedItems)
            {
                text_caiyanzhi.Text = li.SubItems[0].Text;
                text_biaozhunzhi.Text = li.SubItems[1].Text;
            }
        }

        private void com_shebei_TextChanged(object sender, EventArgs e)
        {
            sname = com_shebei.Text;
           


            ///显示标定内容
            listView1.Items.Clear();
            string pathbd = "";
            pathbd = System.Windows.Forms.Application.StartupPath + pathbd + "\\标定数据.ini";
            string path2 = string.Format(@"{0}", pathbd);
            Ini(path2);

            string sbiaodingshuju = "";
            sbiaodingshuju = ReadValue("标定", com_shebei.Text);

            if (sbiaodingshuju.Length <= 0)
            {
                return;
            }
            string[] sbdsj = sbiaodingshuju.Split(';');
            string[] sbdfr = sbdsj[0].Split(',');
            string[] sbdfs = sbdsj[1].Split(',');
            listView1.Items.Clear();
            float[] ffr = new float[sbdfr.Length - 1];
            float[] ffs = new float[sbdfr.Length - 1];
            for (int i = 0; i < sbdfr.Length - 1; i++)
            {
                float.TryParse(sbdfr[i], out ffr[i]);
                float.TryParse(sbdfs[i], out ffs[i]);
                ListViewItem li = new ListViewItem();
                li.SubItems[0].Text = sbdfr[i];
                li.SubItems.Add(sbdfs[i]);
                listView1.Items.Add(li);
            }

            int iwidth = pictureBox1.Width;
            int iheight = pictureBox1.Height;
            float x1 = 0, y1 = iheight;

            float fx = (ffr[ffr.Length - 1] - ffr[0]) / iwidth;
            float fy = (ffs[ffs.Length - 1] - ffs[0]) / iheight;

            //  float fy = iwidth / ffr.Length - 1;
            //fs为x轴，fr为y轴
            Graphics gas = pictureBox1.CreateGraphics();
            gas.Clear(pictureBox1.BackColor);
            //   Pen p = new Pen(Color.Red, 2);
            for (int i = 0; i < sbdfr.Length - 1; i++)
            {
                Graphics g = pictureBox1.CreateGraphics();
                //g.Clear(pictureBox1.BackColor);
                Pen p = new Pen(Color.Red, 1);

                float float1 = (ffr[i] - ffr[0]) / fx;
                float float2 = iheight - ((ffs[i] - ffs[0]) / fy);
                g.DrawLine(p, x1, y1, float1, float2);
                x1 = float1;// fx * (ffr[i] - ffr[0]);
                y1 = float2;// fy * (ffs[i] - ffs[0]);
            }

            Graphics gex = pictureBox1.CreateGraphics();
            //g.Clear(pictureBox1.BackColor);
            Pen p1 = new Pen(Color.Green, 1);
            gex.DrawLine(p1, 0, iheight, iwidth, 0);
            ///
        }

        public void BubbleSort(float[] R)//冒泡排序
        {
            int i, j; //交换标志 
            float temp=0;
            bool exchange;
            for (i = 0; i < R.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前，交换标志应为假
                for (j = R.Length - 2; j >= i; j--)
                {
                    if (R[j + 1] < R[j])　//交换条件
                    {
                        temp = R[j + 1];
                        R[j + 1] = R[j];
                        R[j] = temp;
                        exchange = true; //发生了交换，故将交换标志置为真 
                    }
                }
                if (!exchange) //本趟排序未发生交换，提前终止算法 
                {
                    break;
                }
            }
        }
        public void tiaoling()
        {
            for (int i = 0; i < 8; i++)
            {
                fAIDataZero[i] = m_mainform.DAC.fAIData[i];
            }
        }

        private void com_shebei_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void BiaoDing_FormClosed(object sender, FormClosedEventArgs e)
        {
            t1.Abort();
            t1.DisableComObjectEagerCleanup();
        }

        private void but_tiaoling_Click(object sender, EventArgs e)
        {
            tiaoling();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void but_bqpks_Click(object sender, EventArgs e)
        {
            m_mainform.BianPinQi(true);
            ipinglv = 256 * 1;
            Thread.Sleep(3000);
            m_mainform.BianPinQiSpeed(ipinglv);//设置频率 256 对应2.56
        }

        private void but_bqpgb_Click(object sender, EventArgs e)
        {
            m_mainform.BianPinQi(false);
        }

        private void but_sdzj_Click(object sender, EventArgs e)
        {
            ipinglv = ipinglv + 256 * 1;
            m_mainform.BianPinQiSpeed(ipinglv);//设置频率 256 对应2.56
        }

        private void but_sdjd_Click(object sender, EventArgs e)
        {
            ipinglv = ipinglv - 256 * 1;
            m_mainform.BianPinQiSpeed(ipinglv);//设置频率 256 对应2.56
        }

        private void BiaoDing_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }

        private void btnsendwl_Click(object sender, EventArgs e)
        {
            double dsc=0;
            double.TryParse(txtfs.Text,out dsc);
            m_mainform.DAC.PutVol(dsc);
            //float ireturn = m_mainform.DAC.getcyz("涡流输出", (float)dsc);//获取采样值
            //MessageBox.Show(ireturn.ToString());
            //float ireturn2 =  m_mainform.DAC.getwoliu("涡流输出", (float)dsc);//获取采样值(string sName, float fSourceData)//获取采样值tcyz("涡流输出", (float)dsc);//获取采样值
            //MessageBox.Show(ireturn2.ToString());
        }

        private void text_jisuanzhi_DoubleClick(object sender, EventArgs e)
        {
            skinBut_add.Visible = true;
            skinBut_del.Visible = true;
            skinBut_set.Visible = true;
        }

    }
}
